import wx from '../../../subwe/bridge';
import WXPage from "../../../subwe/page";
const app = getApp();
import { Index } from '../../../apis/index';
const API = new Index();
var interval = null;
var intime = 90; // 值越大旋转时间越长  即旋转速度
WXPage({
  data: {
    host: '',
    commentId: 0,
    notificationId: 0,
    drawGoodsList: [],
    topShowGoodsList: [],
    drawGoodsItem: {},
    drawStep: 1,
    // 3-展示关闭盒子 4-展示打开盒子

    resultList: [],
    luckPosition: 5,
    drawLuck: true,
    list: [{
      show: false,
      phone: "137***3126",
      name: "抽中保温杯"
    }, {
      show: false,
      phone: "130***8566",
      name: "抽中迷你小风扇"
    }, {
      show: false,
      phone: "151***2562",
      name: "抽中玻璃女生可爱便携带吸管喝水杯"
    }, {
      show: false,
      phone: "147***3599",
      name: "抽中萌萌小怪兽毛绒公仔"
    }, {
      show: false,
      phone: "130***2571",
      name: "抽中迷你小风扇"
    }, {
      show: false,
      phone: "132***3721",
      name: "太空萌虎一拖三充电线"
    }, {
      show: false,
      phone: "130***7769",
      name: "抽中萌萌小怪兽毛绒公仔"
    }, {
      show: false,
      phone: "152***3307",
      name: "太空萌虎一拖三充电线"
    }, {
      show: false,
      phone: "130***3622",
      name: "抽中玻璃女生可爱便携带吸管喝水杯"
    }, {
      show: false,
      phone: "136***9577",
      name: "抽中25元现金红包"
    }, {
      show: false,
      phone: "177***5316",
      name: "抽中纪梵希小猪皮"
    }, {
      show: false,
      phone: "176***2933",
      name: "抽中苹果电脑充电器"
    }],
    prize: [{
      id: "1",
      name: "????",
      img: 'https://zmapi.cnman.cn/static/wx/draw/box@2x.png',
      is_prize: '1',
      status: false
    }, {
      id: "2",
      name: "????",
      img: 'https://zmapi.cnman.cn/static/wx/draw/box@2x.png',
      is_prize: '1',
      status: false
    }, {
      id: "3",
      name: "????",
      img: 'https://zmapi.cnman.cn/static/wx/draw/box@2x.png',
      is_prize: '1',
      status: false
    }, {
      id: "4",
      name: "????",
      img: 'https://zmapi.cnman.cn/static/wx/draw/box@2x.png',
      is_prize: '1',
      status: false
    }, {
      id: "5",
      name: "????",
      img: 'https://zmapi.cnman.cn/static/wx/draw/box@2x.png',
      is_prize: '1',
      status: false
    }, {
      id: "6",
      name: "????",
      img: 'https://zmapi.cnman.cn/static/wx/draw/box@2x.png',
      is_prize: '1',
      status: false
    }, {
      id: "7",
      name: "????",
      img: 'https://zmapi.cnman.cn/static/wx/draw/box@2x.png',
      is_prize: '1',
      status: false
    }, {
      id: "8",
      name: "????",
      img: 'https://zmapi.cnman.cn/static/wx/draw/box@2x.png',
      is_prize: '1',
      status: false
    }, {
      id: "9",
      name: "????",
      img: 'https://zmapi.cnman.cn/static/wx/draw/box@2x.png',
      is_prize: '1',
      status: false
    }],
    draw_time: '1'
  },
  onLoad(ev) {
    this.setData({
      host: wx.getStorageSync("host")
    });
    this.setData({
      commentId: Number(ev.id || 10006)
    });
    this.setData({
      notificationId: Number(ev.nId || 10636)
    });
    this.getDrawGoodsList(true);
    this.getDrawGoodsPrizeList();
  },
  getDrawGoodsPrizeList() {
    API.getDrawGoodsPrizeList().then(res => {
      let list = res.result || [];
      if (list.length === 0) {} else if (list.length < 15) this.setData({
        list: [...list, ...this.data.list]
      });else this.setData({
        list: [...list]
      });
      this.data.list[0].show = true;
      this.data.list[1].show = true;
      this.data.list[2].show = true;
      this.setData({
        list: this.data.list
      });
      setInterval(ev => this.showList(), 1000 * 4.5);
    });
  },
  showGoodsListIcon(list) {
    let dList = [{
      icon: 'https://zmapi.cnman.cn/static/wx/draw/goods2@2x.png'
    }, {
      icon: 'https://zmapi.cnman.cn/static/wx/draw/goods3@2x.png'
    }, {
      icon: 'https://zmapi.cnman.cn/static/wx/draw/goods4@2x.png'
    }, {
      icon: 'https://zmapi.cnman.cn/static/wx/draw/goods5@2x.png'
    }];
    for (let item of list) item.icon = this.data.host + item.icon;
    if (list.length > 5) this.setData({
      topShowGoodsList: [...list]
    });else this.setData({
      topShowGoodsList: [...list, ...dList]
    });
  },
  // 中奖名单展示
  showList() {
    let len = 3;
    let index = 0;
    let targetIndex = 0;
    for (let item of this.data.list) {
      if (item.show) targetIndex++;
      if (targetIndex === len) {
        if (this.data.list[index + 1]) {
          this.data.list[index + 1].show = true;
          this.data.list[index - len + 1].show = false;
        } else {
          for (let i = 0; i < this.data.list.length; i++) this.data.list[i].show = i < len;
        }
        this.setData({
          list: this.data.list
        });
        return;
      }
      index++;
    }
  },
  // 打开抽奖
  openDraw() {
    this.setData({
      drawStep: 4
    });
    this.setCommentGoods();
  },
  // 计算中奖概率
  calculateWinning(list) {
    let allNum = 0;
    let ratioTarget = 0;
    let randomNum = Math.random() * 100;
    for (let item of list) allNum += item.probability;
    for (let item of list) {
      let ratio = item.probability / allNum * 100;
      let oldRatio = ratioTarget;
      ratioTarget += ratio;
      if (randomNum >= oldRatio && randomNum <= ratioTarget) return item;
    }
    return {};
  },
  // 查询抽奖商品列表
  getDrawGoodsList(isShow) {
    console.log('getDrawGoodsList');
    API.getDrawGoodsList({
      pageNo: 1,
      pageSize: 99
    }).then(res => {
      this.setData({
        drawGoodsList: res.result.data || []
      });
      if (isShow) return this.showGoodsListIcon(res.result.data || []);
      this.setData({
        drawGoodsInfo: this.calculateWinning(this.data.drawGoodsList)
      });
      this.setData({
        luckPosition: parseInt(Math.random() * 8)
      });
      this.stop(this.data.luckPosition);
    });
  },
  // 提交抽奖结果
  setCommentGoods() {
    let {
      id,
      name
    } = this.data.drawGoodsInfo;
    if (!id) return wx.showModal({
      title: '提示',
      content: '很遗憾未中奖',
      showCancel: false,
      success: function (res) {
        wx.redirectTo({
          url: '/pages/serviceHome/serviceHome'
        });
      }
    });
    API.setCommentGoods({
      id: this.data.commentId,
      goodsId: id
    }).then(res => {
      // wx.showModal({
      //   title: '提示', content: `恭喜你抽中了 ${name}, 审核通过后将发放奖励`, showCancel: false,
      //   success: function (res) {
      //     wx.redirectTo({url: '/pages/serviceMy/workList/workList'})
      //   }
      // })
    });
  },
  goToWorkList() {
    wx.redirectTo({
      url: `/pages/workOrderDetail/workOrderDetail?id=${this.data.notificationId}&commentId=${this.data.commentId}&notificationType=${9}`
    });
  },
  drawLuck() {
    if (this.data.draw_time === 0) return wx.showToast({
      title: '您的抽奖次数已经用光了',
      icon: 'none'
    });
    if (!this.data.drawLuck) return;
    this.setData({
      drawLuck: false
    });
    let that = this;
    clearInterval(interval);
    var index = 0;
    interval = setInterval(function () {
      if (index > 8) {
        index = 0;
        that.data.prize[8].status = false;
      } else if (index != 0) {
        that.data.prize[index - 1].status = false;
      }
      that.data.prize[index].status = true;
      that.setData({
        prize: that.data.prize
      });
      index++;
    }, intime);
    console.log(this.data.prize);

    // 查询商品列表
    that.getDrawGoodsList();

    //  let stoptime = 2000;
    //  setTimeout(function () {
    //    that.stop(that.data.luckPosition);
    //  }, stoptime)
  },

  stop: function (which) {
    var e = this;
    //清空计数器
    clearInterval(interval);
    //初始化当前位置
    var current = -1;
    var prize = e.data.prize;
    for (var i = 0; i < prize.length; i++) {
      if (prize[i] == 1) {
        current = i;
      }
    }
    //下标从1开始
    var index = current + 1;
    e.stopLuck(which, index, intime, 10);
  },
  stopLuck: function (which, index, time, splittime) {
    var that = this;
    //值越大出现中奖结果后减速时间越长
    var prize = that.data.prize;
    setTimeout(function () {
      //重置前一个位置
      if (index > 7) {
        index = 0;
        prize[7].status = false;
      } else if (index != 0) {
        prize[index - 1].status = false;
      }
      //当前位置为选中状态
      prize[index].status = true;
      that.setData({
        prize: prize
      });
      //如果旋转时间过短或者当前位置不等于中奖位置则递归执行
      //直到旋转至中奖位置
      if (time < 400 || index != which) {
        //越来越慢
        splittime++;
        time += splittime;
        //当前位置+1
        index++;
        that.stopLuck(which, index, time, splittime);
      } else {
        //1秒后显示弹窗
        setTimeout(function () {
          that.setData({
            drawStep: 3
          });
          // let prize_info = that.data.prize[which];
          // let title = '';
          // if (prize_info.is_prize == 1) {
          //   title = '恭喜你抽中了' + prize_info.name;
          //   let resultList=[]
          //   resultList.push(prize_info)
          //   that.setData({
          //     resultList:that.data.resultList.concat(resultList)
          //   })
          //   console.log(that.data.resultList)
          // } else {
          //   title = '很遗憾未中奖';
          // }
          // wx.showModal({
          //   title: '提示',
          //   content: title,
          //   showCancel: false,
          //   success: function (res) {
          //     if (res.confirm) {
          //       let draw_time=that.data.draw_time;
          //       draw_time--;
          //       console.log(draw_time)
          //       that.setData({
          //         drawLuck: true,
          //         luckPosition: 0,
          //         draw_time:draw_time
          //       })
          //     }
          //   }
          // })
        }, 1000);
      }
    }, time);
  },
  upper(e) {
    console.log(e);
  },
  lower(e) {
    console.log(e);
  },
  scroll(e) {
    console.log(e);
  },
  scrollToTop() {
    this.setAction({
      scrollTop: 0
    });
  }
});